var HashMap = require('HashMap');
var DragNode = require('DragNode');
var Container = require('Container');
cc.Class({
    extends: cc.Component,

    properties: {
        containers:{
            default:[],        // The default value will be used only when the component attaching
            type:Container,
            serializable: true,   // optional, default is true
            tooltip:'所有能拖进的容器集合',
        },
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.node.on(cc.Node.EventType.TOUCH_START,this._onTouchStart,this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE,this._onTouchMove,this);
        this.node.on(cc.Node.EventType.TOUCH_END,this._onTouchEnd,this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL,this._onTouchCancel,this);
        this.touchMap = new HashMap();
        let winSize = cc.winSize;
        this.node.width = winSize.width;
        this.node.height = winSize.height;
    },
    start () {

    },
    _onTouchStart(event){
        var self = this;
        var point = self._toLocalPoint(event.getLocation());
        var children = this.node.children;
        for (var j = 0;j<children.length;j++){
            var child = children[j];
            var drag = child.getComponent(DragNode);
            if (drag && child.getBoundingBox().contains(point)){
                //调用开始被拖拽事件
                var isDrag = drag.onDragStart(point);
                if (isDrag){
                    self.touchMap.put(event.getID(),drag);
                }
            }
        }
    },
    _toLocalPoint(v2){
        // let winSize = cc.winSize;
        v2.x -= this.node.width/2;
        v2.y -= this.node.height/2;
        return v2;
    },
    _onTouchMove(event){
        var self = this;
        if (self.touchMap.size()>0){
            if (self.touchMap.hasKey(event.getID())){
                var drag = self.touchMap.get(event.getID());
                var point = self._toLocalPoint(event.getLocation());
                drag.onDragMove(point);
            }
        }
        // cc.log('触摸移动:',event);
    },
    _onTouchEnd(event){
        var self = this;
        if (self.touchMap.size()>0){
            if (self.touchMap.hasKey(event.getID())){
                var drag = self.touchMap.get(event.getID());
                self.touchMap.remove(event.getID())
                drag.onDragEnd(self.containers);
            }
        }
    },
    _onTouchCancel(event){
        var self = this;
        if (self.touchMap.size()>0){
            if (self.touchMap.hasKey(event.getID())){
                var drag = self.touchMap.get(event.getID());
                self.touchMap.remove(event.getID())
                drag.onDragEnd(self.containers);
            }
        }
    },
    // update (dt) {},
});
